const express = require('express');
const router = express.Router();
const db = require('../config/db');
const authenticateToken = require('../middleware/auth');

/**
 * @route   GET /api/statistics
 * @desc    获取用户统计信息
 * @access  Private
 */
router.get('/', authenticateToken, async (req, res) => {
  try {
    const { userId } = req.user;

    // 实时计算统计数据
    const [stats] = await db.query(`
      SELECT 
        COUNT(*) as total_count,
        SUM(CASE WHEN completed = 0 THEN 1 ELSE 0 END) as pending_count,
        SUM(CASE WHEN completed = 1 THEN 1 ELSE 0 END) as completed_count,
        SUM(CASE WHEN priority = 'high' THEN 1 ELSE 0 END) as high_priority_count,
        SUM(CASE WHEN priority = 'medium' THEN 1 ELSE 0 END) as medium_priority_count,
        SUM(CASE WHEN priority = 'low' THEN 1 ELSE 0 END) as low_priority_count
      FROM memos
      WHERE user_id = ? AND is_deleted = 0
    `, [userId]);

    res.json({
      code: 200,
      message: '获取成功',
      data: {
        totalCount: stats[0].total_count || 0,
        pendingCount: stats[0].pending_count || 0,
        completedCount: stats[0].completed_count || 0,
        highPriorityCount: stats[0].high_priority_count || 0,
        mediumPriorityCount: stats[0].medium_priority_count || 0,
        lowPriorityCount: stats[0].low_priority_count || 0
      }
    });
  } catch (error) {
    console.error('获取统计信息错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * @route   GET /api/statistics/priority
 * @desc    获取各优先级的备忘录数量
 * @access  Private
 */
router.get('/priority', authenticateToken, async (req, res) => {
  try {
    const { userId } = req.user;

    const [priorityStats] = await db.query(`
      SELECT 
        priority,
        COUNT(*) as count
      FROM memos
      WHERE user_id = ? AND is_deleted = 0
      GROUP BY priority
    `, [userId]);

    // 格式化数据
    const result = {
      high: 0,
      medium: 0,
      low: 0
    };

    priorityStats.forEach(stat => {
      result[stat.priority] = stat.count;
    });

    res.json({
      code: 200,
      message: '获取成功',
      data: result
    });
  } catch (error) {
    console.error('获取优先级统计错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: error.message
    });
  }
});

/**
 * @route   GET /api/statistics/overview
 * @desc    获取完整的统计概览
 * @access  Private
 */
router.get('/overview', authenticateToken, async (req, res) => {
  try {
    const { userId } = req.user;

    // 获取基本统计
    const [basicStats] = await db.query(`
      SELECT 
        COUNT(*) as total_count,
        SUM(CASE WHEN completed = 0 THEN 1 ELSE 0 END) as pending_count,
        SUM(CASE WHEN completed = 1 THEN 1 ELSE 0 END) as completed_count
      FROM memos
      WHERE user_id = ? AND is_deleted = 0
    `, [userId]);

    // 获取优先级统计
    const [priorityStats] = await db.query(`
      SELECT 
        priority,
        COUNT(*) as count,
        SUM(CASE WHEN completed = 0 THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN completed = 1 THEN 1 ELSE 0 END) as completed
      FROM memos
      WHERE user_id = ? AND is_deleted = 0
      GROUP BY priority
    `, [userId]);

    // 获取最近的备忘录
    const [recentMemos] = await db.query(`
      SELECT id, content, priority, remind_time, completed, created_at
      FROM memos
      WHERE user_id = ? AND is_deleted = 0
      ORDER BY created_at DESC
      LIMIT 5
    `, [userId]);

    // 格式化优先级统计
    const priorityData = {
      high: { total: 0, pending: 0, completed: 0 },
      medium: { total: 0, pending: 0, completed: 0 },
      low: { total: 0, pending: 0, completed: 0 }
    };

    priorityStats.forEach(stat => {
      priorityData[stat.priority] = {
        total: stat.count,
        pending: stat.pending,
        completed: stat.completed
      };
    });

    res.json({
      code: 200,
      message: '获取成功',
      data: {
        basic: {
          totalCount: basicStats[0].total_count || 0,
          pendingCount: basicStats[0].pending_count || 0,
          completedCount: basicStats[0].completed_count || 0
        },
        priority: priorityData,
        recentMemos: recentMemos
      }
    });
  } catch (error) {
    console.error('获取统计概览错误:', error);
    res.status(500).json({
      code: 500,
      message: '服务器错误',
      error: error.message
    });
  }
});

module.exports = router;
